--
-- Created by IntelliJ IDEA.
-- User: galileoliu
-- Date: 2019/6/3
-- Time: 11:51
-- Copyright (c) 2018      Figure Inc.

----传奇武器技能按钮
local Armature = require("app.public.avatar.Armature")
local Skill = require("app.public.dao.Skill")
local SkillLegendButton = MClass("SkillLegendButton")
local TAP_ZORDER = 1
local TAG_CD = 101
local TAG_EFFECT = 103

function SkillLegendButton:ctor()
    --self.root 默认为根节点
    self.mTouchWidget = self.root

    --icon
    self.mSkillIcon = self:findChild("icon")

    --cd
    self.mCdNode = self:findChild("Panel_cd")
    self.mCdMask = self.mCdNode:findChild("img_cd")
    self.mCdMask:setVisible(false)
    self.cdSprite = self.mCdNode:getChildByTag(TAG_CD)
    if not self.cdSprite then
        self.cdSprite = cc.ProgressTimer:create(self.mCdMask)
        self.cdSprite:setType(cc.PROGRESS_TIMER_TYPE_RADIAL)
        self.cdSprite:setScaleX(-1)
        self.cdSprite:setMidpoint(cc.p( 0.5, 0.5 ))
        self.cdSprite:setPosition(self.mCdMask:getPosition())
        self.cdSprite:setTag(TAG_CD)
        self.mCdNode:addChild(self.cdSprite, -1)
    end

    self.mCdNum = self.mCdNode:findChild("time")

    self.restrictedEffectsNode = self:findChild("stop")
    --ongoing
    self.mOnGoing = self:findChild("ongoing")
    if cc.isAlive(self.mOnGoing) and self.mOnGoingAction == nil then
        self.mOnGoingAction = cc.CSLoader:createTimeline(Res.SkillOnGoing)
        self.mOnGoing:runAction(self.mOnGoingAction)
        self.mOnGoingAction:gotoFrameAndPause(0)
    end
    self.effectNode = self:findChild("effect")

    local scheduler = display.newNode()
    self.scheduler = scheduler
    self:addChild(scheduler)

    self:enableNodeEvents()

    self:init()
end

function SkillLegendButton:onExit()
    self.mCdNode:setVisible(false)
    if cc.isAlive(self.effectArmature) then
        self.effectArmature:removeFromParent()
        self.effectArmature = nil
    end
    self:unregisterScriptHandler()
end

function SkillLegendButton:getName()
    return self.name
end

function SkillLegendButton:getIcon()
    return self.icon
end

function SkillLegendButton:getDes()
    return self.desc or "Test"
end

function SkillLegendButton:init()
    BattleUIEvent:addObjToFrameUpdate(self,SkillLegendButton.updateFrame)

    self.effectArmature = self:getChildByTag(TAG_EFFECT)
    if not self.effectArmature then
        self.effectArmature = Armature.create({path=Res.SkillButtonPreEffectPath,armatureName=Res.SkillButtonPreEffectName,animationName="",skeletonName=Res.SkillButtonPreEffectName})
        self.effectNode:addChild(self.effectArmature, 9999)
        self.effectArmature:setScale(0.65)
    end
    self.effectArmature:setVisible(false)
end

function SkillLegendButton:playPreEffect()
    if cc.isAlive(self.effectArmature) then
        if not self.effectArmature:isVisible() then
            self.effectArmature:setVisible(true)
            self.effectArmature:playAni(
                {
                    name = "loop",
                })
        end
    end
end

function SkillLegendButton:playRleaseEffect()
    if cc.isAlive(self.effectArmature) then
        self.effectArmature:setVisible(true)
        self.effectArmature:stop()
        self.effectArmature:playAni(
            {
                name = "dead",
                playTimes = 1,
                completeCallback = function(sender)
                    if cc.isAlive(self.effectArmature) then
                        self.effectArmature:setVisible(false)
                    end
                end
            })
    end
end

function SkillLegendButton:playOnGoing()
    if cc.isAlive(self.mOnGoingAction) then
        self.mOnGoingAction:gotoFrameAndPlay(0, self.mOnGoingAction:getDuration(), false)
    end
end

function SkillLegendButton:setSkillEnable(bEnable)
    self.bSkillEnable = bEnable
end

function SkillLegendButton:setData(data)
    if not data then return end
    self.skillCfg = data.skillCfg
    self.classSkillId = data.classSkillId
    self.skillId =  self.skillCfg:getId()
    self.bBusy = false
    local function clickCallBack(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            self.bShowTips = false
            self.startTime = app.session:getServerTime() or app:getUTCTime()
            BattleUIEvent:dispatchEvent(BattleUIEvent.TYPE.BATTLE_CANCEL_AUTO)
            self.bBusy = true
            self:setLocalZOrder(TAP_ZORDER)
        elseif eventType == ccui.TouchEventType.ended or eventType == ccui.TouchEventType.canceled then
            -- --如果在取消按钮内，则取消
            self.duleTime = app.session:getServerTime() or app:getUTCTime()
            if eventType == ccui.TouchEventType.ended then
                if self.startTime then
                    local tempX, tempY = self:getPosition()
                    local posX, posY = self:getParent():toWorldPosition(tempX, tempY)
                    local skillId = self.skillCfg:getId()
                    if self.duleTime - self.startTime < Constant.BattleCancelInterval then
                        BattleUIEvent:dispatchEvent(BattleUIEvent.TYPE.SKILL_SELECT, {skillId = skillId, posX = posX})
                    end
                end
            end
            self.bBusy = false
            self.startTime = nil
            self.bShowTips = false
            app:dispatchCustomEvent("EVENT_CLOSE_FLOAT")
        end
    end
    self.mTouchWidget:addTouchEventListener(clickCallBack)
    self:setSkill(self.classSkillId)
end

function SkillLegendButton:updateFrame()
    -- 新手战不需要显示tips
    if not app:isBattleGuideComp() then
        return
    end

    --长按tips
    if not self.startTime then
        return
    end
    self.duleTime = app.session:getServerTime() or app:getUTCTime()
    if self.duleTime - self.startTime > Constant.BattleCancelInterval and not self.bShowTips then
        self.bShowTips = true
        local param =
        {
            tipsType = Enums.TipsType.classSkill,
            dataTemp = self._tipSkill,
        }
        app:dispatchCustomEvent("EVENT_OPEN_FLOAT", { params=param })
    end
end

function SkillLegendButton:setSkill(classSkillId)
    if classSkillId then
        local classSkill = GD:getClassSkill(classSkillId)
        self.classSkill = classSkill
        self.name = L(classSkill.name)
        self.desc = L(classSkill.des)
        self.icon = Res.skillIconPath..classSkill.icon..".png"
        self._tipSkill = Skill.new()
        self._tipSkill:read({ uid = classSkillId })
    end

    if self.icon then
        self.mSkillIcon:loadTexture(self.icon)
    end

    self.cd = 0
end

function SkillLegendButton:setRestrictedEffects(restrictedEffects)
    self.restrictedEffectsNode:setVisible(false)
    for _, v in ipairs(restrictedEffects) do
        if v == Enums.BuffEffectsLogic.BE_Silence then
            self.restrictedEffectsNode:setVisible(true)
        elseif v == Enums.BuffEffectsLogic.BE_Stune then
            self.restrictedEffectsNode:setVisible(true)
        end
    end
end

function SkillLegendButton:scheduleOnce(action,delay)
    local actions = {}
    if delay then
        table.insert(actions,cc.DelayTime:create(delay))
    end
    table.insert(actions,action)
    local newAction = cc.Sequence:create(actions)
    self.scheduler:runAction(newAction)
end

function SkillLegendButton:canPlayRlsEffectUntil(delay)
    if not self.inRleaseEffect then
        self.inRleaseEffect = true
    else
        return
    end
    local actions = {}
    local action = cc.CallFunc:create(function()
        self:playRleaseEffect()
    end)
    table.insert(actions,action)
    if delay then
        table.insert(actions,cc.DelayTime:create(delay))
    end
    local actionEnd = cc.CallFunc:create(function()
        self.inRleaseEffect = false
    end)
    table.insert(actions,actionEnd)
    local newAction = cc.Sequence:create(actions)
    self.scheduler:runAction(newAction)
end

function SkillLegendButton:setSkillCD(cd, cdD)
    if cd and cd > 0 then
        self.mCdNode:setVisible(true)
        self.mCdNum:setString(string.format("%.1f", cd/1000))
        local percent = cd/cdD
        self.cdSprite:setPercentage(100*percent)

        if cd == 100 then
            local action = cc.CallFunc:create(function()
                self:playOnGoing()
            end)
            self:scheduleOnce(action,0.1)
        end
    else
        self.mCdNode:setVisible(false)
    end
end

function SkillLegendButton:setButtonState(alive, restrictedEffects, isPending, preReleaseFinish, cd, cdD, isDeploy, deployLeftTime, deployD,propertyCan, priorityPass, isReady,skill,subscribeSkillId,showCanBreak)
    if cc.isDead(self.root) then
        return
    end
    self.skill = skill
    local restricted = not skill:canIgnoreRestrictEffects(restrictedEffects)
    local enabled = alive and cd <= 0 and propertyCan and priorityPass and (not isPending) and (not restricted) and (not preReleaseFinish) --and isReady
    self:setSkillEnable(enabled)

    if self.skillId == subscribeSkillId then --预约
        self.mCdNode:setVisible(false)
        self:playPreEffect()
    else
        if preReleaseFinish then
            self:setSkillCD(cdD,cdD)
            self:canPlayRlsEffectUntil(1.0)
        else
            if cc.isAlive(self.effectArmature) then
                self.effectArmature:setVisible(false)
            end
            self:setSkillCD(cd,cdD)
        end
    end

    if restricted then
        if cd > 0 then
            self.restrictedEffectsNode:setVisible(false)
        else
            self:setRestrictedEffects(restrictedEffects)
        end
    else
        self.restrictedEffectsNode:setVisible(false)
        if enabled then
            self.restrictedEffectsNode:setVisible(false)
        end
    end
end

function SkillLegendButton:getSkillId()
    if self.skillCfg == nil then
        return
    end
    return self.skillCfg:getId()
end

return SkillLegendButton